package org.example.project.bookstore.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.bean.Alipay;
import org.example.bean.Order;
import org.example.bean.OrderItem;
import org.example.bean.RocketMQOrder;
import org.example.mapper.OrderItemMapper;
import org.example.project.bookstore.service.AlipayService;
import org.example.project.bookstore.service.OrderService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:Liu
 * @Testname:AlipayServiceImpl
 * @Date:2025/8/26 10:58
 */
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {
    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("${notifyUrl}")
    private String notifyUrl;
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;
    @SneakyThrows
    public String pay(Alipay alipay,String logisticsId) {
        log.info("开始执行支付操作：{}", alipay);
        // 产生支付宝的客户端
        AlipayClient client = new DefaultAlipayClient(gatewayUrl, appId, privateKey,
                "json", charset, publicKey, signType);
        // 产生交易对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置回调
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl(notifyUrl);
        // 设置支付参数
        String s = JSONArray.toJSONString(alipay);
        request.setBizContent(s);
        // 执行
        String body = client.pageExecute(request).getBody();
        //定时器 去检测是否成功
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.schedule(()->{
            query(alipay.getOut_trade_no(),logisticsId);
        },1, TimeUnit.MINUTES);
        return body;
    }

    @Resource
    private OrderService orderService;
    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @SneakyThrows
    public JsonResult query(String orderId,String logisticsId) {
        log.info("查看订单状态");
        AlipayClient client = new DefaultAlipayClient(gatewayUrl, appId, privateKey,
                "json", charset, publicKey, signType);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Alipay alipay = new Alipay();
        alipay.setOut_trade_no(orderId);
        request.setBizContent(JSONArray.toJSONString(alipay));
        AlipayTradeQueryResponse response = client.execute(request);
        String tradeStatus = response.getTradeStatus();
        switch (tradeStatus) {
            case"TRADE_SUCCESS"->{
                log.info("用户成功支付了");
                // 1. 判断状态是否修改了
                Order byId = orderService.getById(orderId);
                int status = byId.getStatus();
                try {
                    if (status == 1) {
                        // 2.1 修改status
                        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", orderId);
                        updateWrapper.eq("status",1);
                        updateWrapper.set("status", 2);
                        boolean b = orderService.update(updateWrapper);
                        log.info("b:{}", b);
                        // 2.2 向rocketMQ发送一笔半事务消息
                        // 图书ID、扣减的数量、订单ID，物流收货人姓名、电话以及地址
                        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
                        wrapper.eq("order_id", orderId);
                        List<OrderItem> orderItems = orderItemMapper.selectList(wrapper);
                        RocketMQOrder rocketMQOrder = new RocketMQOrder();
                        rocketMQOrder.setOrderId(orderId);
                        rocketMQOrder.setLogisticsId(logisticsId);
                        rocketMQOrder.setOrderItems(orderItems);
                        rocketMQOrder.setTotalPrice(alipay.getTotal_amount());
                        rocketMQOrder.setUserId(orderId);
                        rocketMQOrder.setAlipayClient(client);
                        String body = JSONArray.toJSONString(rocketMQOrder);
                        Message<String> message = MessageBuilder.withPayload(body).build();
                        // 2.3 获取到订单详情信息
                        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction("order01", "order:transaction", message, body);
                        log.info("transactionSendResult{}", transactionSendResult);
                    }
                } catch (MessagingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return ResultTool.success("success");
    }
}
